
package com.xiaoma.myaudience.biz.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.adapter.HeadlineAdapter;
import com.xiaoma.myaudience.biz.adapter.HomeHotListAdapter;
import com.xiaoma.myaudience.biz.adapter.HomeListAdapter;
import com.xiaoma.myaudience.biz.adapter.HotAdapter;
import com.xiaoma.myaudience.biz.model.HomeInfoModel;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.FirstPageInfoTask;
import com.xiaoma.myaudience.biz.task.HeadlineInfoTask;
import com.xiaoma.myaudience.biz.view.HeadlineGallery;
import com.xiaoma.myaudience.biz.view.HorizontalListView;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;

/**
 * 首页推荐页面.
 * 
 */
public class HomeActivity extends BaseActivity implements  OnItemClickListener, OnClickListener {
    private static final String TAG = "HomeActivity";
    private static final int DIALOG_REFRESH = 0;
    private static final int MENU_REFRESH = Menu.FIRST;
    
    private FirstPageInfoTask mFirstPageInfoTask;
    private HeadlineGallery mHeadlineGallery;
    private HeadlineInfoTask mHeadlineInfoTask;
    
    private int inttype = 0;
	private HorizontalListView listView;
	private HomeListAdapter activityAdapter;
	private List<Map<String, Object>> activityMaps;
    public static final String ACTIVITY_CATEGORY = "activity_category";
    
	List<Map<String, Object>> hotActivityMaps;
	HorizontalListView hotListView;
	HomeHotListAdapter hotAdapter;
	
	List<Map<String, Object>> newActivityMaps;
	HomeHotListAdapter newAdapter;
	HorizontalListView newListView;
	
    public static List<Map<String, Object>> headLine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_page_layout);
       
        setNetEaseTitle(R.string.home_tab);
        setNetEaseTitleGravity(Gravity.CENTER);
        setNetEaseTitleBarVisibility(View.VISIBLE);
        setNetEaseTitleIcon(R.drawable.home_title_icon);
        findViewById(R.id.recomend_title).setOnClickListener(this);
        
        String content = PrefHelper.getString(this, "json", "");
        if (!TextUtils.isEmpty(content)) {
			JSONObject json = null;
			try {
				json = new JSONObject(content);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			initData(ModelUtils.json2Map(json));
		}
    }
    
    @Override
    protected void onRestart() {
    	// TODO Auto-generated method stub
    	super.onRestart();
    }
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	execute(null);
    }
    private void execute(Map map) {
    	 cancel();
         mHeadlineInfoTask = new HeadlineInfoTask(this, DataAsyncTask.TASK_FIRST_PAGE_INFO, this);
         mHeadlineInfoTask.execute(map);
	}
    
    private void cancel() {
    	if (mHeadlineInfoTask != null) {
            mHeadlineInfoTask.cancel(true, true);
        }
        mHeadlineInfoTask = null;
    }

    private void initData(Map<String, Object> objMap) {
    	List<Map<String, Object>> headlines = null;

    	if (objMap == null || objMap.size()<1) {
    		Tips("无数据");
    		return;
		}
    	headlines = ModelUtils.getListMapValue(objMap, HomeInfoModel.PARAM_ADVERTS);
    	headLine = headlines;
		List<Map<String, Object>> oblist = ModelUtils.getListMapValue(objMap, "events");
    	switch (inttype) {
		case 1:
			if (oblist == null || oblist.size() < 1) {
				Tips("无数据");
			}else{
				activityMaps.addAll(oblist);
				activityAdapter.notifyDataSetChanged();
			}
	        return;
		case 2:
			if (oblist == null || oblist.size() < 1) {
				Tips("无数据");
			}else{
				hotActivityMaps.addAll(oblist);
				hotAdapter.notifyDataSetChanged();
			}
			return;
		case 3:
			if (oblist == null || oblist.size() < 1) {
				Tips("无数据");
			}else{
				newActivityMaps.addAll(oblist);
				newAdapter.notifyDataSetChanged();
			}
			return;
		default:
			break;
		}
    	activityMaps = ModelUtils.getListMapValue(objMap, HomeInfoModel.PARAM_RECOMMOND_EVENTS);
    	hotActivityMaps = ModelUtils.getListMapValue(objMap, HomeInfoModel.PARAM_HOTPICS);
    	newActivityMaps = ModelUtils.getListMapValue(objMap, HomeInfoModel.PARAM_NEWPICS);
    	HeadlineAdapter headlineAdapter = new HeadlineAdapter(this, headlines);
    	
        if (activityMaps == null) {
        	activityMaps = new ArrayList<Map<String,Object>>();
        }
        if (hotActivityMaps == null) {
            hotActivityMaps = new ArrayList<Map<String,Object>>();
        }
        if (newActivityMaps == null) {
			newActivityMaps = new ArrayList<Map<String,Object>>();
		}
        
        if (mHeadlineGallery == null) {
            mHeadlineGallery = (HeadlineGallery) findViewById(R.id.headline_gl);
            mHeadlineGallery.setOnItemClickListener(this);
        }
        mHeadlineGallery.setAdapter(headlineAdapter);
        
        activityAdapter = new HomeListAdapter(this, activityMaps);
        listView = (HorizontalListView) findViewById(R.id.recommend_list);
        listView.setAdapter(activityAdapter);
        listView.setOnItemClickListener(this);
        
        hotAdapter = new HomeHotListAdapter(this, hotActivityMaps, 1);
        hotListView = (HorizontalListView) findViewById(R.id.hot_list);
        hotListView.setAdapter(hotAdapter);
        hotListView.setOnItemClickListener(this);
        
        newAdapter = new HomeHotListAdapter(this, newActivityMaps, 2);
        newListView = (HorizontalListView) findViewById(R.id.new_list);
        newListView.setAdapter(newAdapter);
        newListView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    	Map<String, Object> item = null;
		item = (Map<String, Object>) adapter.getItemAtPosition(position-1);
		String datelinekey = "dateline";
    	if(position==adapter.getAdapter().getCount()-1){
    		if(adapter.getAdapter() instanceof HomeListAdapter) {
    			inttype = 1;
    		}else if (adapter.getAdapter() instanceof HomeHotListAdapter) {
    			HomeHotListAdapter myadapter = (HomeHotListAdapter)adapter.getAdapter();
    			int mType = myadapter.getMtype();
    			inttype = mType+1;
    			if(inttype==2){datelinekey="hot";}
    		}
    		String dateline = ModelUtils.getStringValue(item, datelinekey);
			Map<String,String> map = new HashMap<String, String>();
			map.put("line", dateline);
			map.put("type", String.valueOf(inttype));
			
			execute(map);
    	}else{
    	item = (Map<String, Object>) adapter.getItemAtPosition(position);
    	if (item != null) {
	    	if(adapter.getAdapter() instanceof HomeHotListAdapter) {
	    		Intent intent = new Intent(HomeActivity.this, ReviewActivity.class);
	    		intent.putExtra(HomeInfoModel.PARAM_PICID, 
	    				ModelUtils.getStringValue(item, HomeInfoModel.PARAM_PICID));
	    		intent.putExtra(HomeInfoModel.PARAM_EVENTID, 
    					ModelUtils.getStringValue(item, HomeInfoModel.PARAM_EVENTID));
    			intent.putExtra(HomeInfoModel.PARAM_TYPE, "1");
	    		startActivity(intent);
	    	} else if (adapter.getAdapter() instanceof HomeListAdapter) {
    			Intent intent = new Intent(HomeActivity.this, ActivitysDetailActivity.class);
    			intent.putExtra(HomeInfoModel.PARAM_EVENTID, 
    					ModelUtils.getStringValue(item, HomeInfoModel.PARAM_EVENTID));
    			startActivity(intent);
    		} else if (adapter.getAdapter() instanceof HeadlineAdapter) {
    			String type = ModelUtils.getStringValue(item, HomeInfoModel.PARAM_TYPE);
    			if ("1".equals(type)) {
    				String content = ModelUtils.getStringValue(item, HomeInfoModel.PARAM_CONTENT);
    				String title = ModelUtils.getStringValue(item, HomeInfoModel.PARAM_TITLE);
    				showAddInfoDialog(content, title);
				}else if ("2".equals(type)) {
					Intent intent = new Intent(HomeActivity.this, ActivitysDetailActivity.class);
					intent.putExtra(HomeInfoModel.PARAM_EVENTID, 
							ModelUtils.getStringValue(item, HomeInfoModel.PARAM_EVENTID));
					startActivity(intent);
				}
			}
		}
    	}
    }
    
    private void showAddInfoDialog(String string, String title) {
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		 dlg.show();
		 Window window = dlg.getWindow();
		 window.setContentView(R.layout.add_event_view_layout);
		 WindowManager.LayoutParams params = window.getAttributes();
		 params.width = LayoutParams.FILL_PARENT;
		 params.height = LayoutParams.FILL_PARENT;
		 window.setAttributes(params);
		 ((TextView)window.findViewById(R.id.base_title_bar_title)).setText(title);
		 ((TextView)window.findViewById(R.id.title)).setText(Html.fromHtml(string));
		 window.findViewById(R.id.show_comments_back_original).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlg.dismiss();
			}
		});
	}

    @Override
    public boolean onCreateOptionsNeteaseMenu(Menu menu) {
//    	((AudienceMainActivity)getParent()).onCreateOptionsNeteaseMenu(menu);
//        menu.add(0, MENU_REFRESH, 0, R.string.menu_refresh).setIcon(R.drawable.ic_menu_refresh);
        
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (!((AudienceMainActivity) getParent()).onMenuItemSelected(featureId, item)) {
            switch (item.getItemId()) {
                case MENU_REFRESH:
                    execute(null);
                    break;
            }
        }
        return true;
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_REFRESH: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage(getText(R.string.refresh_button));
                dialog.setOnCancelListener(new OnCancelListener() {                    
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mFirstPageInfoTask != null) {
                            mFirstPageInfoTask.cancel();
                            mFirstPageInfoTask = null;
                        }                        
                    }
                });
                return dialog;
            }
        }
        return super.onCreateDialog(id);
    }
    
    public void refresh() {
        if (mFirstPageInfoTask != null) {
            mFirstPageInfoTask.cancel();
        }
        mFirstPageInfoTask = new FirstPageInfoTask(this, this);
        mFirstPageInfoTask.execute();
        showDialog(DIALOG_REFRESH);        
    }
    
    @Override
    public void onPostExecute(int what, Object o) {
        super.onPostExecute(what, o);
        switch (what) {
            case DataAsyncTask.TASK_FIRST_PAGE_INFO:
            	Map<String, Object> objMap = (Map<String, Object>) o;
            	if (objMap == null) {
					return;
				}
            	
            	String json = null;
            	JSONObject jsonObject = ModelUtils.map2Json(objMap);
            	if (jsonObject != null) {
					json = jsonObject.toString();
				}
            	
            	PrefHelper.putString(HomeActivity.this, "json", TextUtils.isEmpty(json) ? "" : json);
                initData(objMap);
//                dismissDialog(DIALOG_REFRESH);
                break;
        }
    }
    
    public void onShowOrHide(boolean show) {
        if (mHeadlineGallery != null) {
            mHeadlineGallery.startAutoScroll(show);
        }
    }

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(HomeActivity.this, ActivitySelectActivity.class);
		switch (v.getId()) {
		case R.id.recomend_title:
			intent.putExtra(ACTIVITY_CATEGORY, "S所有");
			intent.putExtra("index", "0");
			HomeActivity.this.startActivity(intent);
			break;

		default:
			break;
		}
	}
}
